<template>
    <div class='login-container' @keypress='keypress($event)'>
        <!-- 登录区 钉钉环境下不显示 自动登录；非钉钉下/钉钉环境下不存在这个用户 显示 正常登录 -->
        <el-row   v-if = 'isDing=="notInDingTalk" ? pcshow : headershow' >
            <div class="color-black mb40  ft20" align='center' >
                    用户登录
            </div>
            <div class="login-body">
                <el-form ref="loginForm" :model="loginForm" label-width="80px" :rules='rules'>
                    <el-form-item label="" prop='username'>
                        <el-input v-model="loginForm.username" align='left' placeholder='请输入用户名/手机号' v-focus  ><template slot="prepend"><font-awesome-icon icon="user"  /></template></el-input>
                    </el-form-item>
                    <el-form-item label="" prop='password'>
                        <el-input show-password v-model.trim="loginForm.password" align='left' placeholder='请输入密码'><template slot="prepend"><font-awesome-icon icon="unlock-alt"  /></template></el-input>
                    </el-form-item>
                </el-form>
                <el-button type="primary"   @click.native.prevent="submitForm('loginForm')"  class='login-btn'  :loading='displayLoading'  >登录</el-button>
            </div>
        </el-row>
    </div>
</template>

<script charset="utf-8" type="text/javascript">
/*interface*/
//非钉钉下 登录获取token
import { getToken } from '@/api/login'
//我的消息接口
import  {  ListMessge  }  from  '@/api/homework/index'
  //钉钉下 获得企业id并获取免登录码 登录获取token
import  {  get_corpid,login_code }  from '@/api/dingding/index'

/*state*/
import {mapGetters} from 'vuex'

export default {
    data() {
        return {
            /*登录按钮等待加载状态*/
            displayLoading: false,

            /*登录form*/
            loginForm: {
              username: '',
              password: ''
            },
            /*登录form=》rules*/
            rules: {
              username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
              password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
            },

            /*登录区 在非钉钉环境中 显示*/
            pcshow:true,
            /*判断当前是否是钉钉环境 是否需要显示等录区*/
            isDing:'notInDingTalk',
        }
    },
    created() {
        this.pageInit()
        let isMobile = this.isPC_Mobile() //false 是pc端
        this.$store.commit("setisMobile",isMobile);
    },
    methods: {
        /*初始化 页面  S*/
        /*判断环境，进入钉钉免登录*/
        pageInit(){
            let that = this
            let dd = this.$dingding
            /*登录区 在钉钉环境中 不显示*/
            this.isDing = dd.env.platform
            // alert(this.isDing)//notInDingTalk--pc端 手机端  android，pc，--手机端钉钉，pc端钉钉
            if(dd.env.platform != 'notInDingTalk'){

                let config = {
                    corpId:'ding09ea39d79cb30d9135c2f4657eb6378f',//online
                    // corpId:'ding2df5664bd6af06c135c2f4657eb6378f',//local
                    // corpId:':dingfe7121bf77f91f2235c2f4657eb6378f',//测试
                }
                //获取corpId
                // get_corpid().then(res=>{
                //   if(res.data.flag == true){
                //       config.corpId = res.data.CORPID
                //   }
                // })
                /*钉钉相关在ready里执行 需要鉴权则要加上dd.config*/
                dd.ready(function() {
                    /*钉钉pc端打开不支持showPreloader，hidePreloader*/
                    if(dd.env.platform !='pc'){
                        /*等待加载*/
                        dd.device.notification.showPreloader({
                            text: "使劲加载中..", //loading显示的字符，空表示不显示文字
                            showIcon: true, //是否显示icon，默认true
                            onSuccess : function(result) {
                                /*请求免登录*/
                                dd.runtime.permission.requestAuthCode({
                                    corpId: config.corpId, // 企业id
                                    onSuccess: function (info) {
                                        let code = info.code // 通过该免登授权码可以获取用户身份
                                        // alert(122321)
                                        login_code(code).then(response=>{
                                            
                                            if(response.status  == 200){ 
                                                that.commin_login_main(response)
                                            }
                                            /*加载结束*/
                                            dd.device.notification.hidePreloader({
                                                onSuccess : function(result) {
                                                    /*{}*/
                                                },
                                                onFail : function(err) {}
                                            })
                                        })
                                        .catch(error=>{
                                            that.$store.commit("setheadershow",true);
                                            alert('请求出错')
                                            /*加载结束*/
                                            dd.device.notification.hidePreloader({
                                                onSuccess : function(result) {
                                                    /*{}*/
                                                },
                                                onFail : function(err) {

                                                }
                                            })
                                        }) 
                                    },
                                    onFail : function(err) {
                                        alert('出错，请联系管理员！')
                                    }
                                });
                            },
                            onFail : function(err) {}
                        })
                        
                        dd.error(function(error){
                            /**
                            {
                               errorMessage:"错误信息",// errorMessage 信息会展示出钉钉服务端生成签名使用的参数，请和您生成签名的参数作对比，找出错误的参数
                               errorCode: "错误码"
                            }
                            **/
                            alert('dd error: ' + JSON.stringify(error));
                        });
                    }
                    else{
                        /*请求免登录*/
                                dd.runtime.permission.requestAuthCode({
                                    corpId: config.corpId, // 企业id
                                    onSuccess: function (info) {
                                        let code = info.code // 通过该免登授权码可以获取用户身份
                                        // alert(122321)
                                        login_code(code).then(response=>{
                                            
                                            if(response.status  == 200){ 
                                                that.commin_login_main(response)
                                            }
                                        })
                                        .catch(error=>{
                                            that.$store.commit("setheadershow",true);
                                            alert('请求出错')
                                            
                                        }) 
                                    },
                                    onFail : function(err) {
                                        alert('出错，请联系管理员！')
                                    }
                                });
                    }
                })  
            }
        },
        /*初始化 页面  E*/

        //提交登录 S
        submitForm(formName) {
            let that = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    that.displayLoading = true
                    
                    getToken(this.loginForm.username, this.loginForm.password)
                    .then(response => {
                        if(response.status  == 200){ 
                            this.commin_login_main(response)
                        }
                    }) 
                    .catch(error=>{//catch(error) 是上面response执行到有错误的地方他就调到这里 ，因为 that.$message({type:'warning',message:response.data.msg})执行错误所以他在在这里解
                      setTimeout(function(){
                              that.displayLoading = false
                          },500)
                    })
                 
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        /*公共登录部分（钉钉自动登录、手动登录）*/
        commin_login_main(response){
            let that = this
            this.$message({type:'success',message:'登录成功'})
            //把返回token存储
            sessionStorage.setItem('currentUser', JSON.stringify({
                name      : response.data.username 
            }))
            sessionStorage.setItem('token', response.data.token)
            sessionStorage.setItem('tokenId', response.data.tokenId)
            sessionStorage.setItem('routers', JSON.stringify(response.data.routers))
            
            //vuex sessionStorage  vuex存的是会变化的，需要响应所有用到这个数据的地方  sessStorage 存的基本是不动值
            that.$store.commit("setusername",response.data.username);
            that.$store.commit("setroleNames",response.data.roleNames);
            that.$store.commit("setcacheRoute",['item','company','product','examine']);
            

            /*登录之后需要马上显示消息数*/
            // let mesnum ;
            // ListMessge({pageNo:1,pageSize:10}).then(res=>{
            //   if(res.data.flag == true){
            //       // console.log('login')
            //       mesnum = res.data.notViewCount
            //       that.$store.commit("setmessageNum",mesnum);
            //   }
            // })
            /*初始化首页路由*/
            this.initIndexRouter()
            // console.log(this.$route)
            let redirect = decodeURIComponent(
                this.$route.query.redirect || "/homework"
            )
            this.$router.push(redirect);
        },
        /*初始化首页路由*/
        initIndexRouter(){
            let indexRouter = {
                path: '/',
                name: "index",
                component: resolve => require(['@/views/home/index'], resolve),
                children: [...this.generateChildRouters()]
            }
            this.$router.addRoutes([indexRouter])
        },
        /*生成嵌套路由（子路由）*/
        generateChildRouters(){
            let that = this
            //如果还没有存在 需要返回一个空对象，否则会报错 Cannot convert undefined or null to object 因为children数组中存的值不能为undefined
            if (!window.sessionStorage.getItem('routers')) {
                return {}
            }

            let routers = JSON.parse(sessionStorage.getItem('routers'))
            /*子路由数组，最后由函数return*/
            let childRouters = []
            /*初始化按钮访问权限*/
            let button_limit = [] 

            for(let router of routers) {
                try {
                  /*路由存储*/
                  if(router.isRouter == '1'  ){
                      let routerProps = JSON.parse(router.routerCode)
                      if(routerProps){
                          // let index_props = 'views/homework/index'  //将路径拆解成 '@/' + ... 这样才能正确解析
                          let childRouter = {
                              path: routerProps.path,
                              name: routerProps.name,
                              component:resolve => require(['@/' + routerProps.component], resolve), //  ()=>import('@/views/homework/index')不  routerProps.component , //resolve => require([routerProps.component], resolve)不
                              meta: routerProps.meta
                          }
                          // console.log(childRouter)
                          childRouters.push(childRouter)
                      }
                  }
                  /*页面操作权限存储*/
                  if(router.isMenu == '0'){ 
                      button_limit.push(router)
                  }
                }catch (ex) {
                    console.warn(ex.message)
                }
            }
            that.$store.commit("setbutton_limit",button_limit);
            // console.log(childRouters)
            return childRouters
        },
        /*键盘按下事件触发 登录按钮事件*/
        keypress(e){
            if(e.charCode == 13){
                this.submitForm('loginForm')
            }
        },
        //提交登录 E
    },
    mounted(){
        
    },
    computed: {
        ...mapGetters(['headershow'])
    },
}
</script>

<style  scoped>
/*登录页*/
.login-container{padding-top:120px;}
.login-body{width: 500px;margin:20px auto 0; }
.login-body .el-input{width: 338px;}
.login-btn{background:#00AAFF; color: #fff; width:338px;font-size: 18px; cursor: pointer;margin-left:80px;margin-top:30px;}

/*适应移动端*/
@media screen and (max-width: 414px) {
   .login-body  .el-input{width: 200px;}
   .login-body  .login-btn{margin:0 auto;display: block}
   .login-body{width: auto;margin:20px auto 0; }
}
</style>
